<?php

namespace app\controller\api;

use app\common\model\PayOrderModel;
use app\common\model\SchoolModel;
use app\model\AdminMerchantNet;
use app\model\AdminPayOrder;
use app\model\AdminRechargeRecord;
use app\model\AdminStaff;
use app\model\AdminStaff as StaffModel;
use app\model\AdminStaffIcCard;
use app\model\AdminStudentDormitory;
use app\util\BEIBEIGFUtil;
use app\util\RequestUtil;
use app\util\ReturnCode;
use app\util\Strs;
use app\util\TLPAYUtil;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use think\facade\Validate;

class PayOrder extends Base {

    /**
     * 获取订单列表
     */
    public function getPayOrder() {
        $data     = Request::param(['uuid', 'begin', 'end', 'page']);
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $validate = Validate::rule([
            'uuid|用户标识' => 'require',
        ]);
        if (!$validate->check($data)) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, $validate->getError());
        }
        $staff = AdminStaff::where([
            'is_delete' => 0,
            'status' => AdminStaff::AUDIT_PASS,
            'uuid' => $data['uuid'],
        ])->find();
        if (!$staff) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '账号不存在或未审核通过');
        }

        $listObj = (new AdminPayOrder())
            ->where('staff_id', '=', $staff->id)
            ->where('order_status', '<>', 0)
            ->with(['staff', 'school'])
            ->append(['pay_type_text','order_status_text','order_type_text'])
            ->order(['create_time' => 'DESC'])
            ->paginate(['page' => $start, 'list_rows' => $limit])
            ->toArray();

        $listInfo = $listObj['data'];
        foreach ($listInfo as $key => &$value) {
            $value['money'] = $value['money'] / 100;
        }
        return $this->buildSuccess([
            'list' => $listInfo,
            'count' => $listObj['total']
        ]);
    }

    /**
     * 发起统一下单
     */
    public function uniformlyOrder() {
        $data = input('post.');
        $money = input('post.money/f');
        $validate = Validate::rule([
            'uuid|账号' => 'require',
            'pay_type|支付方式' => 'require',
            'tl_pay|通联支付方式' => 'require', // 通联支付特有 wx：微信 zfb：支付宝
            'order_type|充值类型' => 'require',
            'money|充值金额' => 'require'
        ]);
        if (!$validate->check($data)) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, $validate->getError());
        }
        if ($money < 0) {
            return $this->buildFailed(ReturnCode::INVALID, '请输入正确的充值金额');
        }
        $staff = AdminStaff::where([
            'is_delete' => 0,
            'status' => AdminStaff::AUDIT_PASS,
            'uuid' => input('post.uuid/s'),
        ])->find();
        if (!$staff) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '账号不存在或未审核通过');
        }
        if ($staff->user_level == 0) {
            return $this->buildFailed(ReturnCode::INVALID, '暂无水电充值权限');
        }
        $school = SchoolModel::getSchool($staff->school_id);
        if ($school->recharge_min && $school->recharge_min > 0){
            $MIN_MONEY = $school->recharge_min;
            if ($money < $MIN_MONEY) {
                return $this->buildFailed(ReturnCode::INVALID, '最低充值金额 '.$MIN_MONEY.' 元');
            }
        }
//        if ($staff->user_level == 1 && !strpos($school->member_home_menu,'hydropower')) {
//            return $this->buildFailed(ReturnCode::INVALID, '暂无水电充值权限');
//        }
        $merchantNet = AdminMerchantNet::where([
            'school_id' => $staff->school_id,
            'pay_type' =>  input('post.pay_type/d'),
            'merchant_type' => 0 // 水电充值
        ])->find();
        if (!$merchantNet) {
            return $this->buildFailed(ReturnCode::INVALID, '当前学校未开放此方式的在线充值');
        }
        $order_type = input('post.order_type/d');
        $staffIcCard = AdminStaffIcCard::where([
            'staff_id' => $staff->id,
            'is_delete' => 0
        ])->column('student_dormitory_id');
        if (isset($staffIcCard) && count($staffIcCard) == 0) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '账号未分配宿舍，请联系管理员');
        }
        $studentDormitory = AdminStudentDormitory::where('id', 'in', $staffIcCard)
            ->whereNotNull($order_type == 0 ? 'water_no' : 'electric_no')
            ->where($order_type == 0 ? 'water_no' : 'electric_no','<>','')->find();
        if (!$studentDormitory) {
            return $this->buildFailed(ReturnCode::INVALID, '宿舍信息不存在，请联系管理员');
        }
        if ($order_type == 0 && !$studentDormitory->water_no) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '当前宿舍未分配水表设备，请联系管理员');
        }
        if ($order_type == 1 && !$studentDormitory->electric_no) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '当前宿舍未分配电表设备，请联系管理员');
        }
        // 写入支付订单记录
        $payOrderData = [
            'staff_id'       => $staff->id,
            'school_id'       => $staff->school_id,
            'pay_type'      => input('post.pay_type/d', ''),
            'order_status'       => 0,
            'order_type'       => $order_type,
            'device_no' => $order_type == 0 ? $studentDormitory->water_no : $studentDormitory->electric_no,
            'order_no'  => 'NHGM_SDCZ_'.Strs::randString(12, 1),
            'money'        => round($money * 100),
            'order_time'  => time()
        ];
        Db::startTrans();
        $res = AdminPayOrder::create($payOrderData);
        if ($res === false) {
            Db::rollback();
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }
        Db::commit();
        // 反查订单信息
        $payOrder = AdminPayOrder::where('id', $res->id)
            ->with(['school'])
            ->append(['pay_type_text','order_status_text','order_type_text'])
            ->find();
        // 发起支付
        $payOrder['payinfo'] = $this->TLPay($merchantNet, $payOrder, $data['tl_pay']);

        return $this->buildSuccess([$payOrder]);
    }

    // 通联统一支付接口
    function TLPay(AdminMerchantNet $merchantNet, AdminPayOrder $payOrder, string $tl_pay) : string {
        $params = array();
        $params["cusid"] = $merchantNet->merchant_no;
        $params["appid"] = $merchantNet->appid;
        $params["version"] = '11';
        $params["orgid"] = '';
        $params["trxamt"] = $payOrder->money;
        $params["reqsn"] = $payOrder->order_no;
        $params["paytype"] = $tl_pay == 'wx' ? 'W01' : 'A01';
        $params["body"] = '水电在线充值';
        $params["remark"] = '';
        $params["validtime"] = 120;
        $params["acct"] = 'oM4tN4x6Cdp51AYTZCYzPN2E8gLU';
        $params["notify_url"] = $merchantNet->notify_url.'/admin/PayOrder/TLPayNotify';
        $params["limit_pay"] ='';
        $params["sub_appid"] = '';
        $params["subbranch"] = '';
        $params["cusip"] = '';
        $params["idno"] = '';
        $params["truename"] ='';
        $params["fqnum"] ='';
        $params["randomstr"] = 12;
        $params["signtype"] ='RSA';
        $params["sign"] = urlencode(TLPAYUtil::Sign($params, $merchantNet->private_key));//签名
        $paramsStr = TLPAYUtil::ToUrlParams($params);
        $url = "https://vsp.allinpay.com/apiweb/unitorder/pay";
        $rspArray = RequestUtil::post($url, $paramsStr);
        Log::error($params);
        Log::error($rspArray);
//        if(TLPAYUtil::validSign($rspArray, $merchantNet->public_key)){
//            Log::error("验签正确,进行业务处理");
//        } else {
//            Log::error("验签失败");
//        }
        return $rspArray['payinfo'];
    }

    /**
     * 获取订单状态
     */
    public function checkOrderStatus() {
        $data = input('get.');
        $validate = Validate::rule([
            'order_no|订单号' => 'require',
        ]);
        if (!$validate->check($data)) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, $validate->getError());
        }
        $payOrder = AdminPayOrder::where('order_no', $data['order_no'])->find();
        if (!$payOrder) {
            return $this->buildFailed(ReturnCode::INVALID, '订单数据不存在');
        }
        // 处理失败也返回支付成功
        if ($payOrder->order_status == 2) {
            $payOrder->order_status = 1;
        }
        return $this->buildSuccess([$payOrder]);
    }

    /**
     * 充值补发
     */
    public function rechargeRetry() {
        $data = input('post.');
        $validate = Validate::rule([
            'uuid|账号' => 'require',
            'order_no|订单号' => 'require'
        ]);
        if (!$validate->check($data)) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, $validate->getError());
        }
        $payOrder = AdminPayOrder::where('order_no', $data['order_no'])->find();
        if (!$payOrder) {
            return $this->buildFailed(ReturnCode::INVALID, '订单数据不存在');
        }
        $res = BEIBEIGFUtil::rechargeRetry($payOrder->trx_id);
        if (!isset($res['code']) || $res['code'] != '0') {
            return $this->buildFailed(ReturnCode::SERVICE_ERROR, '充值补发失败：'.$res['msg']);
        }
        return $this->buildSuccess([]);
    }
}
